from common.utils.read_file import read_yaml
from common.utils.config_util import EnvConfig
from common.enums.common_enums import DBType
import pymysql


class DBUtil:
    def __init__(self, database_type, database_name, service=None, config=None, config_path=None):
        if config:
            db_config = config
        elif config_path:
            db_config = read_yaml(config_path)
        else:
            db_config = EnvConfig.get_config()
        if database_type.upper() == 'MYSQL':
            # 默认rabbit_platform对应的mysql连接
            service = service if service else 'rabbit_platform'
            mysql_config = db_config['database']['mysql'][service]
            conn = pymysql.connect(
                host=mysql_config['host'],
                port=mysql_config['port'],
                user=mysql_config['username'],
                password=mysql_config['password'],
                database=database_name)
            self.connect = conn
        elif database_type.upper() == 'ORACLE':
            pass
        else:
            raise ValueError(f'database_type值{database_type}不正确！')

    def execute_query(self, sql):
        """ 执行数据库查询 """
        try:
            conn = self.connect
            cursor = conn.cursor()
            cursor.execute(sql)
            values = cursor.fetchall()
            return values
        except Exception:
            conn.rollback()
            raise
        finally:
            cursor.close()

    def execute_insert(self, sqls):
        """ 执行数据库插入 """
        try:
            conn = self.connect
            cursor = conn.cursor()
            # 执行多条sql
            result = []
            if isinstance(sqls, (list, tuple)):
                for sql in sqls:
                    cursor.execute(sql)
                    result.append(cursor.lastrowid)
            # 执行单条sql
            else:
                cursor.execute(sqls)
                result.append(cursor.lastrowid)
            conn.commit()
            return result
        except Exception:
            conn.rollback()
            raise
        finally:
            cursor.close()

    def execute_delete(self, sqls):
        """ 执行数据库删除 """
        try:
            conn = self.connect
            cursor = conn.cursor()
            # 执行多条sql
            result = []
            if isinstance(sqls, (list, tuple)):
                for sql in sqls:
                    cursor.execute(sql)
                    result.append(cursor.lastrowid)
            # 执行单条sql
            else:
                cursor.execute(sqls)
                result.append(cursor.lastrowid)
            conn.commit()
            return result
        except Exception:
            conn.rollback()
            raise
        finally:
            cursor.close()

    def execute_update(self, sqls):
        """ 执行数据库更新 """
        try:
            conn = self.connect
            cursor = conn.cursor()
            # 执行多条sql
            result = []
            if isinstance(sqls, (list, tuple)):
                for sql in sqls:
                    cursor.execute(sql)
                    result.append(cursor.lastrowid)
            # 执行单条sql
            else:
                cursor.execute(sqls)
            conn.commit()
            return result
        except Exception:
            conn.rollback()
            raise
        finally:
            cursor.close()

    def execute_query_without_sql(self, table, column='*', condition=None):
        """ 执行数据库查询 """
        try:
            conn = self.connect
            cursor = conn.cursor()
            sql = 'select {} from {} where 1=1'.format(column, table)
            sql += '' if not condition else ' and ' + condition
            cursor.execute(sql)
            values = cursor.fetchall()
            return values
        except Exception:
            conn.rollback()
            raise

    def close(self):
        self.connect.close()


if __name__ == '__main__':
    # query_sql = "select * from test_table"
    # insert_sql = "insert into test_table(type,double_amt,decimal_amt) VALUES ('初级','10','10')"
    # delete_sql = "delete from test_table where id > 4"
    # update_sql = "update test_table set type = '123' where id > 4"
    # conn = DBUtil('mysql', 'userinterface')
    # # result = conn.execute_query(query_sql)
    # # print(result)
    # # conn.execute_insert(insert_sql)
    # # conn.execute_delete(delete_sql)
    # # conn.execute_update(update_sql)
    # result1 = conn.execute_query_without_sql('test_table', condition='id > 4')
    # print(result1)
    conn1 = DBUtil('mysql', 'userinterface')
    result = conn1.execute_query('select * from test_table')
    print(result)
